package mi.payment.utils.transaction;

import android.os.AsyncTask;

import mi.payment.MyApplication;
import mi.payment.settings.NetworkParamSettings;
import mi.payment.settings.SettlementTransaction;
import mi.payment.settings.SystemParamsSettings;
import mi.payment.settings.TerminalKeyManagementBean;
import mi.payment.constants.Params;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.NetworkDataOperations;
import mi.payment.settings.SettlementTransactionOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TransactionSwitchOperation;
import mi.payment.utils.iso8583.Utils;
import mi.payment.utils.secure.TerminalSecure;
import sunmi.payment.ui.dialog.LoadDialog;

/**
 * 用于管理服务器下发的处理要求的处理
 *
 * @author KenMa on 2017/2/18.
 */

public class ProcessRequireManager {

    /**
     * 处理要求编码	处理要求说明
     * 0	无处理要求
     * 1	下传终端磁条卡参数
     * 2	上传终端磁条卡状态信息
     * 3	重新签到
     * 4	通知终端发起更新公钥信息操作
     * 5	下载终端IC卡参数
     * 6	TMS参数下载
     * 7	卡BIN黑名单下载
     * 8	币种汇率下载（仅在境外使用）/助弄取款 手续费比率下载（仅在境内使用）
     */
    public static void checkProcessCode(int processCode) {
        switch (processCode) {
            case 1:
                //下传终端磁条卡参数
                new ParamsDownloadTask(MyApplication.getInstance()).execute("360", getUploadMAGStatusInfo());
                break;
            case 2:
                //上传终端磁条卡状态信息
                new POSStatusUpload(MyApplication.getInstance()) {
                    @Override
                    protected void onPostExecuteImpl(final String s) {
                        AsyncTask.execute(new Runnable() {
                            @Override
                            public void run() {
                                setUploadMAGStatusInfo(s);
                            }
                        });
                    }
                }.execute("362", "");

                break;
            case 3:
                //重新签到
                new SignTask(MyApplication.getInstance()).execute(Params.newTradeData());
                break;
            case 4:
                //通知终端发起更新公钥信息操作
                new CAPKDownloadTask(MyApplication.getInstance()).execute();
                break;
            case 5:
                //下载终端IC卡参数
                new ICParamsDownloadTask(MyApplication.getInstance()).execute();
                break;
            case 6:
                //TMS参数下载
                break;
            case 7:
                //卡BIN黑名单下载
                break;
            default:
                break;
        }
    }

    /**
     * 同步处理要求
     *
     * @param processCode
     */
    public static void syncCheckProcessCode(int processCode) {
    }

    /**
     * @return 监控报文中存放终端状态信息。其格式为：编码+取值
     */
    private static String getUploadMAGStatusInfo() {
        StringBuilder sb = new StringBuilder();
        NetworkParamSettings tNetworkParamSettings = NetworkDataOperations.getInstance().getNetworkParamSettings();
        SettlementTransaction tSettlementTransaction = SettlementTransactionOperation.getInstance().getSettlementTransaction();
        SystemParamsSettings tSystemParamsSettings = SystemParamsOperation.getInstance().getSystemParamsSettings();
        TerminalKeyManagementBean tTerminalKeyManagementBean = TerminalKeyDataOperations.getInstance().getTerminalKeyManagementBean();
        // 硬件状态
        sb.append("01" + "1");//01	键盘状态	N1	1—正常，0—不正常
        sb.append("02" + "1");//02	密码键盘状态	N1	1—正常，0—不正常
        sb.append("03" + "1");//03	读卡器状态	N1	1—正常，0—不正常
        sb.append("04" + "1");//04	打印机状态	N1	1—正常，0—不正常
        sb.append("05" + "1");//05	显示器状态	N1	1—正常，0—不正常
        // 下载的参数
        sb.append("11" + "60");//11	POS终端应用类型	N2	60
        sb.append("12" + String.format("%02d", Integer.parseInt(tNetworkParamSettings.getCommunicationTimeout())));//12	超时时间	N2	2位数字表示的秒数
        sb.append("13" + tNetworkParamSettings.getTransactionRepeatNum());//13	重试次数	N1	1位数字
        sb.append("14" + "              ");//14	三个交易电话号码之一	N14	14位数字，右补空格
        sb.append("15" + "              ");//15	三个交易电话号码之二	N14	14位数字，右补空格
        sb.append("16" + "              ");//16	三个交易电话号码之三	N14	14位数字，右补空格
        sb.append("17" + "              ");//17	一个管理电话号码	N14	14位数字，右补空格
        sb.append("18" + "0");//18	是否支持小费	N1	1—支持，0—不支持
        sb.append("19" + "00");//19	小费百分比	N2	2位数字，00—99
        sb.append("20" + "0");//20	是否支持手工输入卡号	N1	1—支持，0—不支持
        sb.append("21" + (tSettlementTransaction.isAutomaticSignOut() ? "1" : "0"));//21	是否自动签退	N1	1—自动，0—不自动
        sb.append("23" + tSystemParamsSettings.getCorrectFrequency());//23	交易重发次数	N1	1位数字
        sb.append("25" + TerminalSecure.TMKIndex);//25	主密钥INDEX	N1	1位数字，指明当前使用主密钥序号
        sb.append("27" + "10");//27	满足自动上送的累计笔数	N2	10

        // 通讯统计
        // sb.append("51" + "1");//51	POS拨通率	N12(N4+N5+N3)	从上次成功统计到本次统计的时间段(小时)+5位数字表示的总拨号次数+3位数字表示的拨通率(百分比)
        return sb.toString();
    }

    /**
     * 参数下载时存放参数信息。其格式为：编码+取值
     *
     * @param tMAGStatusInfo 请求返回的字符串
     */
    private static void setUploadMAGStatusInfo(String tMAGStatusInfo) {
        NetworkDataOperations tNetworkParamSettings = NetworkDataOperations.getInstance();
        SettlementTransactionOperation tSettlementTransaction = SettlementTransactionOperation.getInstance();
        SystemParamsOperation tSystemParamsSettings = SystemParamsOperation.getInstance();
        TerminalKeyDataOperations tTerminalKeyManagementBean = TerminalKeyDataOperations.getInstance();
        MerchantSettingsOperation tMerManagerSettings = MerchantSettingsOperation.getInstance();
        TransactionSwitchOperation tTransactionSwitchSetting = TransactionSwitchOperation.getInstance();
        String communicationTimeout = tMAGStatusInfo.substring(6, 8);
        communicationTimeout.startsWith("0");
        communicationTimeout.substring(1, 2);
        tNetworkParamSettings.saveCommunicationTimeout(communicationTimeout);
        tNetworkParamSettings.saveTransactionRepeatNum(Integer.parseInt(tMAGStatusInfo.substring(10, 11)));
        tSettlementTransaction.saveAutomaticSignOut(tMAGStatusInfo.substring(87, 88) == "1" ? true : false);
        tMerManagerSettings.saveMerchantName(tMAGStatusInfo.substring(90, 130));
        tMerManagerSettings.saveMerchantEnglishName(tMAGStatusInfo.substring(90, 130));
        tSystemParamsSettings.saveCorrectFrequency(Integer.parseInt(tMAGStatusInfo.substring(132, 133)));
        tTerminalKeyManagementBean.saveTerminalKeyIndex(tMAGStatusInfo.substring(135, 136));
        String supportTransType = tMAGStatusInfo.substring(138, 146);
        boolean[] supportTransTypeBooleans = Utils.getBinaryFromByte(Utils.hexStr2Bytes(supportTransType));
        tTransactionSwitchSetting.saveConsumption(supportTransTypeBooleans[6]);
        tTransactionSwitchSetting.saveConsumptionRevoke(supportTransTypeBooleans[7]);
        tTransactionSwitchSetting.saveReturnGoods(supportTransTypeBooleans[8]);
        tTransactionSwitchSetting.saveQueryBalance(supportTransTypeBooleans[1]);
        tTransactionSwitchSetting.saveFieldAuth(supportTransTypeBooleans[2]);
        tTransactionSwitchSetting.saveFieldAuthRevoke(supportTransTypeBooleans[3]);
        tTransactionSwitchSetting.saveFieldAuthReq(supportTransTypeBooleans[4]);
        tTransactionSwitchSetting.saveFieldAuthCompleteRevocationNotice(supportTransTypeBooleans[11]);
        tTransactionSwitchSetting.saveFieldAuthCompleteRevocation(supportTransTypeBooleans[5]);
    }

}
